package com.huajiao.review.domain;


import com.huajiao.review.repository.FeedRepository;
import com.huajiao.review.model.FeedInfoEntity;
import com.huajiao.review.vo.Feed;
import com.huajiao.user.contract.model.UserInfoEntity;
import com.huajiao.user.contract.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class FeedDomain {

    @Autowired
    UserService userService;

    @Autowired
    FeedRepository feedRepository;

    //---------------------------查询----------------------------
    public List<FeedInfoEntity> findAll(int pageNum, int pageSize){
        List<FeedInfoEntity> feedInfoEntities = feedRepository.findAll(PageRequest.of(pageNum,pageSize)).getContent();
        return  feedInfoEntities;
    }

    //---------------------------查询----------------------------
    public List<Feed> findAllFeed(int pageNum, int pageSize){
        List<FeedInfoEntity> feedInfoEntities = feedRepository.findAll(PageRequest.of(pageNum,pageSize)).getContent();
        List<Feed> feeds =  feedInfoEntities.stream().map(feedInfoEntity -> {
            UserInfoEntity userInfoEntity = userService.getUserByUserId(feedInfoEntity.getUserId());
            Feed feed = new Feed(feedInfoEntity);
            feed.setNickname(userInfoEntity.getNickname());
            feed.setAvatar(userInfoEntity.getAvatarLink());
            //TODO 点赞列表 通过MongoDB做缓存
            return feed;
        }).collect(Collectors.toList());
        return  feeds;
    }

    public List<FeedInfoEntity> findByUserId(long userId, int pageNum, int pageSize){
        return  feedRepository.findByUserId(userId,PageRequest.of(pageNum,pageSize)).getContent();
    }

    public List<FeedInfoEntity> findByUserId(long userId) {
        return feedRepository.findByUserId(userId);
    }

    public FeedInfoEntity findByFeedId(long feedId) {
        return feedRepository.findByFeedId(feedId);
    }

    public boolean existsByFeedId(long feedId){
        return feedRepository.existsByFeedId(feedId);
    }

    //---------------------------删除----------------------------
    public FeedInfoEntity deleteByFeedId(long feedId) {
        FeedInfoEntity feedInfoEntity = feedRepository.findByFeedId(feedId);
        feedInfoEntity.setIsDeleted((byte) 1);
        return feedRepository.save(feedInfoEntity);
    }

    //---------------------------新增----------------------------
    //---------------------------更改----------------------------
    public FeedInfoEntity save(FeedInfoEntity feedInfoEntity){
        return feedRepository.save(feedInfoEntity);
    }



}
